/*
 * Copyright 2013 Krzysztof Smigielski
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.nilcaream.dirstore.core.common;

import com.nilcaream.dirstore.core.model.ArchiveElement;

import javax.inject.Singleton;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.ZipEntry;

/**
 * TODO
 * <p/>
 * Krzysztof Smigielski 3/26/13 12:38 PM
 */
@Singleton
public class ArchiveMapper {

    public ArchiveElement createFrom(Path root, Path path, BasicFileAttributes attributes) {
        ArchiveElement archiveElement = new ArchiveElement();
        archiveElement.setName(createNameFrom(root.relativize(path), attributes));
        archiveElement.setOriginalSize(attributes.size());
        archiveElement.setLastModified(attributes.lastModifiedTime().toMillis());
        archiveElement.setDirectory(attributes.isDirectory());
        archiveElement.setUri(path.toUri());
        return archiveElement;
    }

    private String createNameFrom(Path path, BasicFileAttributes attributes) {
        StringBuilder builder = new StringBuilder();
        for (int index = 0; index < path.getNameCount() - 1; index++) {
            builder.append(path.getName(index)).append("/");
        }
        builder.append(path.getName(path.getNameCount() - 1));
        if (attributes.isDirectory()) {
            builder.append("/");
        }
        return builder.toString();
    }

    public ArchiveElement createFrom(ZipEntry zipEntry, URI uri) {
        ArchiveElement element = new ArchiveElement();
        element.setName(zipEntry.getName());
        element.setDirectory(zipEntry.isDirectory());
        element.setLastModified(zipEntry.getTime());
        element.setOriginalSize(zipEntry.getSize());
        element.setUri(uri);
        return element;
    }
}
